package so.shanku.essential.fragment;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.*;
import aym.util.getservicesdata.GetServicesDataQueue;
import aym.util.getservicesdata.GetServicesDataUtil;
import aym.util.json.JsonMap;
import aym.util.json.JsonParseHelper;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.view.annotation.ViewInject;
import so.shanku.essential.R;
import so.shanku.essential.activity.*;
import so.shanku.essential.adapter.BrandSearchAdapter;
import so.shanku.essential.app.MyApplication;
import so.shanku.essential.getdata.GetDataConfing;
import so.shanku.essential.getdata.GetDataQueue;
import so.shanku.essential.getdata.JsonKeys;
import so.shanku.essential.getdata.ShowGetDataError;
import so.shanku.essential.utils.Constant;
import so.shanku.essential.utils.Utils;
import so.shanku.essential.utils.searchUtils.CharacterParser;
import so.shanku.essential.utils.searchUtils.PinyinComparator;
import so.shanku.essential.utils.searchUtils.SideBar;
import so.shanku.essential.utils.searchUtils.SortModel;

import java.util.*;

/**
 * Created by Administrator on 2015/9/7.
 */
public class ManBrandListFragment extends BaseFragment {
	@ViewInject(R.id.xlistview_manbrand)
	private ListView xlistview_manbrand;
	@ViewInject(R.id.nodata_layout) //无数据
	private LinearLayout nodataLayout;
	private BrandSearchAdapter brandListAdapter;
	private String id;
	/**
	 * 汉字转换成拼音的类
	 */
	private CharacterParser characterParser;
	/**
	 * 根据拼音来排列ListView里面的数据类
	 */
	private PinyinComparator pinyinComparator;
	private List<SortModel> SourceDateList;
	/**
	 * 品牌搜索引擎
	 */
	@ViewInject(R.id.brand_select_new_sidrbar)
	private SideBar sideBar;
	/**
	 * 弹出的字母
	 */
	@ViewInject(R.id.brand_select_new_dialog)
	private TextView dialog;
	private List<JsonMap<String, Object>> data_DownLoadlist;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.fragment_list_brand, container, false);
		Bundle bundle=getArguments();
		id =bundle.getString(Constant.ID) ;
		initCompont(view);
		// 实例化汉字转拼音类
		characterParser = CharacterParser.getInstance();

		pinyinComparator = new PinyinComparator();
		getData_BrandList();
		return view;
	}
	@Override
	public void onResume() {
		super.onResume();
        if(SourceDateList!=null&&brandListAdapter!=null) {
			brandListAdapter.setList(SourceDateList);
			brandListAdapter.notifyDataSetChanged();
		}
	}
	public void initCompont(View view) {
		ViewUtils.inject(this, view);
	}

//    public void itemClick() {
//        xlistview_manbrand.setOnItemClickListener(new AdapterView.OnItemClickListener() {
//            @Override
//            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//                Bundle bundle = new Bundle();
//                bundle.putString(Constant.VENDOR_ID, data_DownLoadlist.get(position-1).getStringNoNull("VendorId"));
//                bundle.putString(Constant.VENDOR_NAME, data_DownLoadlist.get(position-1).getStringNoNull("ShopName"));
//                activity.jumpTo(ShopActivity.class, bundle, false);
//            }
//        });
//    }


	/**
	 * 获取首页广告数据
	 */
	private final int what_SelectBrandList = 1;

	private void getData_BrandList() {
		loadingToast.show();
		Map<String, Object> params = new HashMap<String, Object>();
		params.put(GetDataQueue.Params_key, GetDataConfing.Key_Str);
		params.put("UserInfoId", Utils.getUserId(getActivity()));
		params.put("BrandTypeId", id);
		params.put("currentPage", 1);
		params.put("pageSize", 1000);
		GetDataQueue queue = new GetDataQueue();
		queue.setActionName(GetDataConfing.GetAction_SelectBrandList);
		queue.setCallBack(callBack);
		queue.setParamsNoJson(params);
		queue.setWhat(what_SelectBrandList);
		getDataUtil.getData(queue);
	}

	private GetServicesDataUtil.IGetServicesDataCallBack callBack = new GetServicesDataUtil.IGetServicesDataCallBack() {

		@Override
		public void onLoaded(GetServicesDataQueue entity) {
			if (entity.isOk()) {

				if (ShowGetDataError.isOkAndCodeIsNot1((getActivity()), entity.getInfo())) {

					if (entity.getWhat() == what_SelectBrandList) {
						List<JsonMap<String, Object>> data = JsonParseHelper.getJsonMap_List_JsonMap(
								entity.getInfo(), JsonKeys.Key_Info);
						data_DownLoadlist = data;
						SourceDateList = filledData(data_DownLoadlist);
						initViews();
						validateData();
					} else if (entity.getWhat() == GetDataConfing.WHAT_GET_FOCUS_ON) {
						List<JsonMap<String, Object>> data = JsonParseHelper.getJsonMap_List_JsonMap(
								entity.getInfo(), JsonKeys.Key_Info);
						try {
							boolean isFocus=data.get(0).getBoolean("IsFocus", false);
							if (isFocus) {
								tv_if_attentioned.setSelected(true);
								tv_if_attentioned.setText(R.string.attentioned);
								MyApplication.getInstance().addAttendBrands(vendorId);
							} else {
								tv_if_attentioned.setSelected(false);
								tv_if_attentioned.setText(R.string.attention);
								MyApplication.getInstance().removeAttendBrands(vendorId);
							}
						} catch (Exception e) {
							e.printStackTrace();
						}
					}

				}
			} else {
				ShowGetDataError.showNetError(getActivity());
			}
			loadingToast.dismiss();
		}
	};

	private void validateData() {
		if(data_DownLoadlist==null||data_DownLoadlist.isEmpty()){
			nodataLayout.setVisibility(View.VISIBLE);
			xlistview_manbrand.setVisibility(View.GONE);
		} else {
			nodataLayout.setVisibility(View.GONE);
			xlistview_manbrand.setVisibility(View.VISIBLE);
		}
	}

//    /**
//     * 当前展示的数据
//     */
//    private List<JsonMap<String, Object>> data_DownLoadlist;
//    private void setAdatper_singleSortlist(final List<JsonMap<String, Object>> data) {
//            this.data_DownLoadlist = data;
//            manBrandListAdapter = new ManBrandListAdapter(getActivity(), data_DownLoadlist,callback2);
//            xlistview_manbrand.setAdapter(manBrandListAdapter);
//    }
//    private ManBrandListAdapter.ItemAttentionChange callback2 = new ManBrandListAdapter.ItemAttentionChange() {
//        @Override
//        public void onStatusChange(int position, ImageView iv_if_attention, TextView tv_if_attention) {
//            iv_if_attentioned = iv_if_attention;
//            tv_if_attentioned = tv_if_attention;
//            String vendorId = data_DownLoadlist.get(position).getStringNoNull("VendorId");
//            isFocus = data_DownLoadlist.get(position).getBoolean("IsFocus", false);
//            if(Utils.isHasLogin(getActivity())){
//                ((MainActivity)getActivity()).getDate_GetFocusOn(callBack, vendorId, getActivity());
//            }
//            else{
//                Intent intent=new Intent(getActivity(),LoginActivity.class);
//                intent.putExtra(ExtraKeys.Key_Msg1,1);
//                startActivity(intent);
//            }
//
//        }
//    } ;

	/**
	 * 为ListView填充数据
	 *
	 * @param date
	 * @return
	 */
	private List<SortModel> filledData(List<JsonMap<String, Object>> date) {
		List<SortModel> mSortList = new ArrayList<SortModel>();
		for (int i = 0; i < date.size(); i++) {
			SortModel sortModel = new SortModel();
			sortModel.setId(date.get(i).getStringNoNull("VendorId"));
			sortModel.setName(date.get(i).getStringNoNull("ShopName"));
			sortModel.setIv_log_url(date.get(i).getStringNoNull("brandLog"));
			sortModel.setTv_msg(date.get(i).getStringNoNull("BusinessCategory"));
			sortModel.setFocus(date.get(i).getBoolean("IsFocus", false));
			//汉字转换成拼音
			String pinyin = characterParser.getSelling(date.get(i).getStringNoNull("ShopName"));
			try {
				String sortString = pinyin.substring(0, 1).toUpperCase();

				// 正则表达式，判断首字母是否是英文字母
				if (sortString.matches("[A-Z]")) {
					sortModel.setSortLetters(sortString.toUpperCase());
				} else {
					sortModel.setSortLetters("#");
				}
				mSortList.add(sortModel);
			} catch (StringIndexOutOfBoundsException e) {
				e.printStackTrace();
			}


		}
		return mSortList;

	}

	private void initViews() {
		sideBar.setTextView(dialog);

		// 根据a-z进行排序源数据
		Collections.sort(SourceDateList, pinyinComparator);
		brandListAdapter = new BrandSearchAdapter(getActivity(), SourceDateList, callback2);
		xlistview_manbrand.setAdapter(brandListAdapter);

		//设置右侧触摸监听
		sideBar.setOnTouchingLetterChangedListener(new SideBar.OnTouchingLetterChangedListener() {

			@Override
			public void onTouchingLetterChanged(String s) {
				//该字母首次出现的位置
				int position = brandListAdapter.getPositionForSection(s.charAt(0));
				if (position != -1) {
					xlistview_manbrand.setSelection(position);
				}

			}
		});

		xlistview_manbrand.setOnItemClickListener(new AdapterView.OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
			                        int position, long id) {
				//这里要利用adapter.getItem(position)来获取当前position所对应的对象

				Bundle bundle = new Bundle();
				bundle.putString(Constant.VENDOR_ID, SourceDateList.get(position).getId());
				bundle.putString(Constant.VENDOR_NAME, SourceDateList.get(position).getName());
				activity.jumpTo(ShopThemeActivity.class, bundle, false);
			}
		});

	}

	private String vendorId;
	private TextView tv_if_attentioned;
	private BrandSearchAdapter.ItemAttentionChange callback2 = new BrandSearchAdapter.ItemAttentionChange() {
		@Override
		public void onStatusChange(int position, TextView tv_if_attention) {
			tv_if_attentioned = tv_if_attention;
			vendorId = SourceDateList.get(position).getId();
			if (Utils.isHasLogin(getActivity())) {
				activity.getDate_GetFocusOn(callBack, vendorId, getActivity());
			} else {
				activity.gotoLogin();
			}
		}
	};
	@Override
	public void onHiddenChanged(boolean hidden) {
		super.onHiddenChanged(hidden);
		try {
			brandListAdapter.setList(SourceDateList);
			brandListAdapter.notifyDataSetChanged();
		} catch (Exception e) {
			e.printStackTrace();
		}

	}
}
